import { Component, Vue, Watch } from 'vue-property-decorator'
import style from './AuthorizeNew.less'
// import styles from '../NewApply/NewApply.less'
import ApplicationTable from '@/modules/applicationTable'
import AuthSeal from '@/modules/authSeal'
import { Route } from 'vue-router'
import { Action } from 'vuex-class'
Component.registerHooks(['beforeRouteLeave'])
@Component({})
export default class AuthorizeNew extends Vue {
  private loading: boolean = false
  private active: number = 0
  private footerHeight: number = 46
  project: any = null
  private selectApp: any[] = []
  private selectSeals: any[] = []

  @Action('project/authorizeManageSeal') private authorizeManageSeal!: any
  @Action('project/authorizeAllManageSeal') private authorizeAllManageSeal!: any

  protected render() {
    return (
      <div class={style.flex}>
        <div class={style.steps}>
          <el-steps active={this.active} align-center>
            <el-step title="添加授权应用" />
            <el-step title="添加授权印章" />
          </el-steps>
        </div>
        {this.active === 0 && (
          <ApplicationTable
            // multi
            select={this.project}
            class={style.orderList}
            style={{
              height: `calc(100% - 115px - ${this.footerHeight}px)`,
            }}
            onDetail={this.projectDetail}
            {...{
              on: {
                'update:select': (val: any) => {
                  this.project = val
                },
              },
            }}
          />
        )}
        {this.active === 1 && (
          <AuthSeal
            class={style.orderList}
            style={{
              height: `calc(100% - 115px - ${this.footerHeight}px)`,
            }}
            onSelectChange={(val: any[]) => {
              this.selectSeals = val
              this.getPaddingBottom()
            }}
            selection={this.selectSeals}
            emptyText="当前查询条件下暂无可授权印章"
          />
        )}
        <div class={style.pagination} ref="footer">
          <div class={style.selection}>
            <p class={style.tagName}>
              <i class="el-icon-info" />
              已选择应用
            </p>
            <div class={style.tags}>
              {this.project && (
                <el-tag
                  key={this.project.projectId}
                  closable={this.active === 0}
                  disable-transitions
                  onClose={() => this.deleteApp()}
                >
                  {this.project.projectName}
                </el-tag>
              )}
            </div>
          </div>
          {(this.selectSeals.length > 0 || this.active === 1) && (
            <div class={style.selection}>
              <p class={style.tagName}>已选择印章</p>
              <div class={style.tags}>
                {this.selectSeals &&
                  this.selectSeals.map((tag: any) => (
                    <el-tag
                      key={tag.id}
                      closable={this.active === 1}
                      disable-transitions={false}
                      onClose={() => this.deleteSeal(tag)}
                    >
                      {tag.sealName}
                    </el-tag>
                  ))}
              </div>
            </div>
          )}
          {this.active === 0 ? (
            <div class={style.operations}>
              <el-button
                type="primary"
                class={['bg-color-blue', { [style.medium]: true }]}
                onClick={this.next}
                disabled={!this.project}
              >
                下一步
              </el-button>
            </div>
          ) : (
            <div class={style.operations}>
              <el-button
                plain
                class={style.btn}
                disabled={this.loading}
                onClick={() => {
                  this.active = 0
                }}
              >
                上一步
              </el-button>
              <el-button
                type="primary"
                class={['bg-color-blue', { [style.medium]: true }]}
                disabled={this.loading || this.selectSeals.length === 0}
                onClick={this.partAuth}
              >
                批量授权
              </el-button>
              <el-button
                type="primary"
                class={['bg-color-blue', { [style.medium]: true }]}
                disabled={this.loading}
                onClick={this.allAuth}
              >
                全部授权
              </el-button>
              <span class={style.info}>
                当前选中<span>{this.selectSeals.length}</span>枚印章，共
                <span>{this.getOrgCount()}</span>
                个机构
              </span>
            </div>
          )}
        </div>
      </div>
    )
  }

  @Watch('active')
  activeChange(val: number) {
    this.getPaddingBottom()
  }

  getOrgCount() {
    // 获取机构数量
    return [...new Set(this.selectSeals.map(seal => seal.organizeUUID))].length
  }

  projectDetail(row: any) {
    this.$router.push({
      name: 'projectDetail',
      query: { id: row.projectId },
    })
  }

  created() {}
  mounted() {
    this.getPaddingBottom()
  }

  getPaddingBottom() {
    this.$nextTick(() => {
      this.footerHeight = (
        (this.$refs.footer as any) || { offsetHeight: 46 }
      ).offsetHeight
    })
  }

  deleteApp() {
    this.project = null
  }
  deleteSeal(seal: any) {
    this.selectSeals = this.selectSeals.filter(
      (select: any) => seal.id !== select.id
    )
  }

  next() {
    if (!this.project) {
      this.$message.warning('请选择授权应用')

      return
    }
    this.active = 1
  }

  partAuth() {
    if (!this.project) {
      this.$message.warning('请选择授权应用')

      return
    }
    if (this.selectSeals.length === 0) {
      this.$message.warning('请选择授权印章')

      return
    }
    const sealCodes = this.selectSeals.map(seal => seal.sealCode) || []
    this.loading = true
    this.authorizeManageSeal({ projectId: this.project.projectId, sealCodes })
      .then((res: any) => {
        this.loading = false
        this.$router.push({
          name: 'authorizeResult',
          query: {
            id: this.project.projectId,
            name: this.project.projectName,
            new: '1',
          },
        })
      })
      .catch(() => {
        this.loading = false
      })
  }

  allAuth() {
    // 全部授权
    if (!this.project) {
      this.$message.warning('请选择授权应用')

      return
    }
    this.$confirm('确认授权当前所有印章？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnPressEscape: false,
      closeOnClickModal: false,
      customClass: 'custom-confirm',
    })
      .then(() => {
        this.confirmAuth()
      })
      .catch(() => {})
  }
  confirmAuth() {
    this.loading = true
    this.authorizeAllManageSeal({ projectId: this.project.projectId })
      .then((res: any) => {
        this.loading = false
        this.$router.push({
          name: 'authorizeResult',
          query: {
            id: this.project.projectId,
            name: this.project.projectName,
            new: '1',
          },
        })
      })
      .catch(() => {
        this.loading = false
      })
  }

  beforeRouteLeave(to: Route, from: Route, next: any) {
    if (
      (to.name !== 'first' || !to.query.login) &&
      to.name !== 'authorizeResult'
    ) {
      this.$confirm('当前操作未完成，确认退出？', '注意', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnPressEscape: false,
        closeOnClickModal: false,
        customClass: 'custom-confirm',
      })
        .then(() => {
          next()
        })
        .catch(() => {
          next(false)
        })
    } else {
      next()
    }
  }
}
